import React, { useEffect, useState } from 'react';
import { Button, Form, Input, Row, Col } from 'antd';
import {
    filterRouterAsync,filterRouter
} from '@/store/features/routeSlice'
import { useSelector, useDispatch } from 'react-redux'
import { useNavigate } from 'react-router-dom';
import { getCaptcha } from "@/api/login";
import './login.less'

import LogoImg from '@img/logo.png'
import LineImg from '@img/login_line.png'

const Login = () => {
    const navigate = useNavigate()
    // 获取state状态和派发
    let { routes } = useSelector(state => state.route),
        dispatch = useDispatch()
    const [key, setKey] = useState(new Date().getTime())
    const [captcha, setCaptcha] = useState('')
    const [loading, setLoading] = useState(false)
    useEffect(() => {
        imgChange()
    }, [])
    const onFinishFailed = (errorInfo) => {
    };
    /**
     * @desc 登录事件
     * @params object {values} 登录表单提交事件
     */
    const onFinish = async (values) => {
        setLoading(true)
        values = { ...values, areaCode: 'admin' }
        React.$post('management/auth/store/login', values).then(data => {
            if (data.code === 0) {
                sessionStorage.setItem('RSnetToken', data.data.token);
                sessionStorage.setItem('roleName', data.data.roleName);
                // this.props.updateUser(data.data);
                React.$post('management/sysStoreIdent/getMenuIdentListByUserId').then(res => {
                    const ident = res.data.idents.map(v => v.identType)
                    // this.props.updateIdent(ident)
                    sessionStorage.setItem('ident', ident)
                    sessionStorage.setItem('user', JSON.stringify(data.data))
                    sessionStorage.setItem('menuList', JSON.stringify(res.data.menus))
                    dispatch(filterRouter(res.data.menus))
                    // window.location.reload();
                    navigate('/home', { replace: true })
                })
            } else {
                imgChange()
            }
            setLoading(false)
        }).catch(e => {
            setLoading(false)
        })
    };
    /**
    * @desc 切换验证图片
    * */
    const imgChange = async () => {
        let res = await getCaptcha(new Date().getTime())
        var binary = "";
        var bytes = new Uint8Array(res);
        var len = bytes.byteLength;
        for (var i = 0; i < len; i++) {
            binary += String.fromCharCode(bytes[i]);
        }
        var base64 = `data:image/png;base64,${window.btoa(binary)}`
        setKey(new Date().getTime())
        setCaptcha(base64)

    };
    return (
        <div className='pages'>
            <div className='formBox'>
                <div className='logoBox'>
                    <img
                        className='logoImg'
                        src={LogoImg}
                    />
                    <p className='loginPt'>登录&nbsp;&nbsp;商家后台</p>
                    <img
                        className='lineImg'
                        src={LineImg}
                    />
                </div>
                <Form
                    className="loginForm"
                    name="loginForm"
                    labelCol={{
                        span: 0
                    }}
                    wrapperCol={{
                        span: 24,
                    }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                >
                    <Form.Item
                        label=""
                        name="loginName"
                        rules={[
                            {
                                required: true,
                                message: '请输入账号!',
                            },
                        ]}
                    >
                        <Input placeholder="请输入账号" style={{ height: 50 }} />
                    </Form.Item>

                    <Form.Item
                        label=""
                        name="password"
                        rules={[
                            {
                                required: true,
                                message: '请输入密码!',
                            },
                        ]}
                    >
                        <Input.Password placeholder="请输入密码" style={{ height: 50 }} />
                    </Form.Item>
                    <Form.Item noStyle>
                        <Row>
                            <Col span={14}>
                                <Form.Item
                                    label=""
                                    name="captcha"
                                    rules={[
                                        {
                                            required: true,
                                            message: '请输入验证码!',
                                        },
                                    ]}
                                >
                                    <Input placeholder="请输入验证码" style={{ height: 50, width: 180 }} maxLength={4} ></Input>
                                </Form.Item>
                            </Col>
                            <Col span={4}>
                                <img src={captcha} key={key} onClick={imgChange} alt="" style={{ height: 50, cursor: 'pointer', display: 'inline-block', borderRadius: 5, marginLeft: 10, marginTop: 0 }} />
                            </Col>
                        </Row>
                    </Form.Item>

                    <Form.Item
                        wrapperCol={{
                            offset: 0,
                            span: 24,
                        }}
                    >
                        <Button type="primary" htmlType="submit" block style={{ height: 50, background: '#1890ff', fontSize: 18 }} >
                            登&nbsp;&nbsp;录
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    )
};
export default Login;
